#coding=utf-8

"""""""""""""""""""""""""""""""""""""""""""""
 # 公用函数库
 # @module
 # @copyright Copyright (c) 2010, pe-dev. inc
 # @author lazyboy <lazyboy.fan@gmail.com>
 # @license
"""""""""""""""""""""""""""""""""""""""""""""

import os
import copy

def write_log(msg):
    """""""""""""""""""""""""""""""""""""""
     # 写系统日志
     #
     # @author   lazyboy <lazyboy.fan@gmail.com>
     # @param    string msg
     # @return   void
     # @todo     
    """""""""""""""""""""""""""""""""""""""
    import syslog
    from config import config
    setting = config().setting()
    method = setting['log']['method']
    syslog.openlog(method,syslog.LOG_LOCAL0)
    syslog.syslog(syslog.LOG_INFO,msg)

def md5(key) :
    """""""""""""""""""""""""""""""""""""""
     # 生成md5加密串
     #
     # @author   lazyboy <lazyboy.fan@gmail.com>
     # @param    string key 待加密字符串
     # @return   string 已加密字符串
     # @todo     
    """""""""""""""""""""""""""""""""""""""
    import hashlib
    hash = hashlib.md5()
    hash.update(key)
    return hash.hexdigest()

def file_put_contents(fileName,contents='',flag=False) :
    """""""""""""""""""""""""""""""""""""""
     # 将一个字符串写入文件(*nix平台 安全)
     #
     # @author   lazyboy <lazyboy.fan@gmail.com>
     # @param    string fileName 要被写入数据的文件名
     # @param    string contents 要写入的数据
     # @param    string flag 附加原有文件之后
     # @return   void
     # @todo     
    """""""""""""""""""""""""""""""""""""""
    mode = (flag and flag.upper() == 'FILE_APPEND') and 'a' or 'wb'
    if os.name == 'posix' :
        import fcntl
        try :
            fp = open(fileName,mode)
            fcntl.flock(fp,fcntl.LOCK_EX)
            fp.write(contents)
            fcntl.flock(fp,fcntl.LOCK_UN)
            fp.close()
            return True
        except IOError :
            print fileName+' does not exists,exit'
            return False
    else :
        fp = open(fileName,mode)
        fp.write(contents)
        fp.close()
        return True

def list2str(data,force=False) :
    """""""""""""""""""""""""""""""""""""""
     # 将列表中的非字符串类型元素转换成字符串类型
     #
     # @author   lazyboy <lazyboy.fan@gmail.com>
     # @param    
     # @return   void
     # @todo     
    """""""""""""""""""""""""""""""""""""""
    if force :
        return map(lambda v:str(v),data)
    else :
        filterList = copy.copy(data)
        for k,v in enumerate(filterList) :
            if isinstance(v,list) :
                filterList[k] = list2str(v)
            elif not isinstance(v,basestring) :
                filterList[k] = str(v)
        return filterList

def ksort(dic,rev=False) :
    """""""""""""""""""""""""""""""""""""""
     # 对字典按照键名排序
     #
     # @author   lazyboy <lazyboy.fan@gmail.com>
     # @param    dict dic 字典对象
     # @param    bool rev 反向排序
     # @return   dict kvList
     # @todo     
    """""""""""""""""""""""""""""""""""""""
    sortedDict = sorted(dic.items(),key=lambda x:x[0],reverse=rev)
    kvList = {'key':[],'value':[]}
    for k,v in sortedDict :
        kvList['key'].append(k)
        kvList['value'].append(v)
    return kvList

def sec2str(format='%Y-%m-%d %H:%M:%S',sec=None) :
    """""""""""""""""""""""""""""""""""""""
     # 将时间戳转换成指定格式字符串
     #
     # @author   lazyboy <lazyboy.fan@gmail.com>
     # @param    
     # @return   void
     # @todo     
    """""""""""""""""""""""""""""""""""""""
    import time
    return sec and time.strftime(format,time.localtime(sec)) or time.strftime(format)

def str2sec(srcStr,format='%Y-%m-%d %H:%M:%S',floatNum=False) :
    """""""""""""""""""""""""""""""""""""""
     # 将指定格式字符串转换成时间戳
     #
     # @author   lazyboy <lazyboy.fan@gmail.com>
     # @param    
     # @return   void
     # @todo     
    """""""""""""""""""""""""""""""""""""""
    import time
    if not isinstance(srcStr,str) :
        srcStr = str(srcStr)

    time_tuple = time.strptime(srcStr,format)
    timestamp = time.mktime(time_tuple)
    return floatNum and timestamp or int(timestamp)

def dateTypeInterval(dataType) :
    """""""""""""""""""""""""""""""""""""""
     # 获取指定类型的日期区间
     #
     # @author   lazyboy <lazyboy.fan@gmail.com>
     # @param    string dataType
     # @return   list
     # @todo     
    """""""""""""""""""""""""""""""""""""""
    import time
    import calendar
    now = time.time()
    year = int(time.strftime('%Y'))
    month = int(time.strftime('%m'))
    lastMonth = month-1 and month-1 or 12
    weekDay = int(time.strftime('%w'))
    if dataType == 'today' :
        interval_from = time.strftime('%Y-%m-%d')
        interval_to = time.strftime('%Y-%m-%d')
    elif dataType == 'yesterday' :
        interval_from = time.strftime('%Y-%m-%d',time.localtime(now-1*24*3600))
        interval_to = interval_from
    elif dataType == 'week' :
        #计算和本周一相差多少天 不能使用 and or 结构(weekDay-1可能为0)
        #错误的表示法 (weekDay and (weekDay-1) or 6)
        if weekDay :
            diffDay = weekDay-1
        else :
            diffDay = 6

        weekBeginStamp = now-diffDay*1*24*3600
        weekEndStamp = weekBeginStamp+6*24*3600
        #weekDay(取值范围0-6) 7-weekDay不能为0
        #weekEndStamp = now+(weekDay and (7-weekDay) or 0)*1*24*3600
        interval_from = time.strftime('%Y-%m-%d',time.localtime(weekBeginStamp))
        interval_to = time.strftime("%Y-%m-%d",time.localtime(weekEndStamp))
    elif dataType == 'last_week' :
        #计算和本周一相差多少天 不能使用 and or 结构(weekDay-1可能为0)
        #错误的表示法 (weekDay and (weekDay-1) or 6)
        if weekDay :
            diffDay = weekDay-1
        else :
            diffDay = 6

        weekBeginStamp = now-diffDay*1*24*3600-7*24*3600
        weekEndStamp = weekBeginStamp+6*24*3600
        interval_from = time.strftime('%Y-%m-%d',time.localtime(weekBeginStamp))
        #tmp = time.mktime(time.strptime(interval_from,'%Y-%m-%d'))
        interval_to = time.strftime("%Y-%m-%d",time.localtime(weekEndStamp))
    elif dataType == 'month' :
        #取本月的天数
        monthDays = calendar.monthrange(year,month)[1]
        monthFormat = (month<10) and '0'+str(month) or str(month)
        interval_from = str(year)+'-'+monthFormat+'-01'
        interval_to = str(year)+'-'+monthFormat+'-'+str(monthDays)
    elif dataType == 'last_month' :
        #取上月的天数
        lastMonthDays = calendar.monthrange(year,lastMonth)[1]
        monthFormat = (lastMonth<10) and '0'+str(lastMonth) or str(lastMonth)
        interval_from = str(year)+'-'+monthFormat+'-01'
        interval_to = str(year)+'-'+monthFormat+'-'+str(lastMonthDays)
    else :
        return False
    return [interval_from,interval_to]
